- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathstack using linked list.py
72 lines (56 loc) · 1.52 KB
/
stack using linked list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
classNode:
def__init__(self,value=None):
self.value=value
self.next=next
classLinkedList:
def__init__(self):
self.head=None
def__iter__(self):
curNode=self.head
whilecurNode:
yieldcurNode
curNode=curNode.next
classStack:
def__init__(self):
self.LinkedList=LinkedList()
def__str__(self):
values=[str(x.value) forxinself.LinkedList]
return'\n'.join(values)
defisEmpty(self):
ifself.LinkedList.head==None:
returnTrue
else:
returnFalse
defpush(self,value):
node=Node(value)
node.next=self.LinkedList.head
self.LinkedList.head=node
#pop
defpop(self):
ifself.isEmpty():
print("there is no element in the stack")
else:
nodeValue=self.LinkedList.head.value
self.LinkedList.head=self.LinkedList.head.next
returnnodeValue
# peek
defpeek(self):
ifself.isEmpty():
print("there is no element in the stack")
else:
nodeValue=self.LinkedList.head.value
returnnodeValue
# delete entire stack
defdelete(self):
self.list=None
customStack=Stack()
customStack.push(1)
customStack.push(2)
customStack.push(3)
print(customStack)
print("\n")
customStack.pop()
print(customStack)
print("\n")
print(customStack.peek())
print(customStack)